/**
 * Copyright (c) <2010>, <SUNNY GUPTA>
 * All rights reserved.

 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *   * Neither the name of the <ORGANIZATION> nor the
 *     names of its contributors may be used to endorse or promote products
 *     derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL <SUNNY GUPTA> BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

package com.gwtp.investmentadvisor.client.common;

import java.util.Date;
import java.util.HashMap;

/**
 * Default Implementation for {@link Cache}.
 * @author Sunny Gupta
 *
 */
public class AppCacheImpl implements AppCache {

  private class CacheValue {

    private final Object value;
    private final long lastUpdateTime;
    private final boolean autoExpire;
    private final long expirationTimeInMs;
    
    public CacheValue(final Object value, final boolean autoExpire, long expirationTimeInMs) {
      this.value = value;
      this.lastUpdateTime = new Date().getTime();
      this.autoExpire = autoExpire;
      this.expirationTimeInMs = expirationTimeInMs;
    }

    public Object getValue() {
      return this.value;
    }

    public long getLastUpateTime() {
      return this.lastUpdateTime;
    }

    public boolean isAutoExpire() {
      return autoExpire;
    }

    public long getExpirationTimeInMs() {
      return expirationTimeInMs;
    }  
  }
  
  private HashMap<Object, CacheValue> map;
  private long autoExpireTimeInMs;
  
  /**
   * Initializes the cache with auto expiration OFF.
   */
  public AppCacheImpl() {
    // Initialize map
    this.map = new HashMap<Object, CacheValue>();
    // By default, autoExpireTime is 0 so that objects never expire
    this.autoExpireTimeInMs = 0;
  }
  
  /**
   * Initialize the cache with auto expiration ON.
   * 
   * @param autoExpireTimeInMs Time in milliseconds after which entries in cache expire
   */
  public AppCacheImpl(long autoExpireTimeInMs) {
    // Initialize map
    this.map = new HashMap<Object, CacheValue>();
    this.autoExpireTimeInMs = autoExpireTimeInMs;
  }
  
  @Override
  public void clear() {
    map.clear();
  }

  @Override
  public Object get(Object key) {
    // Check for null as Cache should not store null values / keys
    if (key == null) {
      throw new NullPointerException("key is null");
    }
    CacheValue cacheValue = map.get(key);
    
    // Check for null
    if (cacheValue == null) {
      return null;
    }
    
    // First check if entry can auto-expire
    if (cacheValue.isAutoExpire()) {
      // Now check if expirationTimeInMs is positive
      long expireTime = 0;
      if (cacheValue.getExpirationTimeInMs() > 0) {
        expireTime = cacheValue.getExpirationTimeInMs();
      } else {
        // Apply default behaviour of cache: Check if autoexpired
        if (cacheValue.isAutoExpire() && this.autoExpireTimeInMs > 0) {
          expireTime = this.autoExpireTimeInMs;
        }
      }
      // Check if expired
      long now = new Date().getTime();
      if (cacheValue.getLastUpateTime() + expireTime > now) {
        // Expired, remove
        remove(key);
        return null;
      }
    }
    
    // Not expired, return the value
    return cacheValue.getValue();
  }

  @Override
  public void put(Object key, Object value) {
    // Put with autoExpire = true
    put(key, value, true, 0);
  }
  
  @Override
  public void put(Object key, Object value, boolean autoExpire) {
    // Put with autoExpire = true
    put(key, value, autoExpire, 0);
  }

  @Override
  public void put(Object key, Object value, long expirationTimeInMs) {
    // Put with autoExpire = true
    put(key, value, true, expirationTimeInMs);
  }
  
  private void put(Object key, Object value, boolean autoExpire, long expirationTimeInMs) {
    // Check for null as Cache should not store null values / keys
    if (key == null) {
      throw new NullPointerException("key is null");
    }
    if (value == null) {
      throw new NullPointerException("value is null");
    }
    
    // Put in map
    map.put(key, new CacheValue(value, autoExpire, expirationTimeInMs));
  }
  
  @Override
  public void remove(Object key) {
    map.remove(key);
  }

  @Override
  public long getLastUpateTime(Object key) {
    // Check for null as Cache should not store null values / keys
    if (key == null) {
      throw new NullPointerException("key is null");
    }
    
    CacheValue value = map.get(key);
    
    // Check for null
    if (value != null) {
      return value.getLastUpateTime();
    } else {
      return -1;
    }
  }

  @Override
  public long getAutoExpireTimeInMs() {
    return autoExpireTimeInMs;
  }

  @Override
  public void setAutoExpireTimeInMs(long autoExpireTimeInMs) {
    // Check for a positive value
    if (autoExpireTimeInMs >= 0) {
      this.autoExpireTimeInMs = autoExpireTimeInMs;
    }
  }

}
